package cn.fastoo.common.dao.system;


import cn.fastoo.common.entity.system.AdminSystemMenu;
import cn.fastoo.common.entity.system.AdminSystemOrganization;
import cn.fastoo.common.sampleframe.dao.FastDao;
import cn.fastoo.common.sampleframe.dao.impl.FastDaoImpl;
import cn.fastoo.common.sampleframe.search.Search;
import cn.fastoo.common.sampleframe.springside.Collections3;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.*;
import java.util.stream.Collectors;


@Component
public class AdminSystemOrganizationDao extends FastDaoImpl<AdminSystemOrganization> implements FastDao<AdminSystemOrganization> {

    public Logger logger = LoggerFactory.getLogger(AdminSystemOrganizationDao.class);

    @Autowired
    @Qualifier("mainDS")
    private void setJt(DataSource ds){
        this.jt = new JdbcTemplate(ds);
    }


    private List<AdminSystemOrganization> cache = null;
    private Map<Long,List<AdminSystemOrganization>> groupByPidMap = null;
    private Map<Long,AdminSystemOrganization> idMap = null;
    private List<AdminSystemOrganization> campus = null;
    @Scheduled(cron = "0/5 * * * * ?")
    private void init(){

       //通过一个组织ID 获取所有子节点ID.
        //如果本人的级别是所在组织
        //          是 数据共享 就获得本部门ID.
        //          不是 就获得个人ID
        cache = find(new Search());
        if(Collections3.isEmpty(cache)){
            return;
        }
        groupByPidMap = cache.stream().collect(Collectors.groupingBy(AdminSystemOrganization::getPid));
        idMap = new HashMap<>();
        campus = new ArrayList<>();
        cache.forEach(t->{
            idMap.put(t.getId(),t);
            if(t.getIsCampus().intValue()==1){
                campus.add(t);
            }
        });

    }

    public  List<AdminSystemOrganization> getAllCampus(){
        return campus;
    }

    public  AdminSystemOrganization getById(Long id){
        return idMap.get(id);
    }

    public  List<AdminSystemOrganization> getChildren(Long topId){
        if(groupByPidMap.get(topId)==null){
            return  null;
        }
        List<AdminSystemOrganization> nodes = groupByPidMap.get(topId);
        List<AdminSystemOrganization> children = new ArrayList<>();
        for(int i =0 ;i<nodes.size();i++){
            AdminSystemOrganization node = nodes.get(i);
            List<AdminSystemOrganization> subCh = getChildren(node.getId());
            if(subCh!=null){
                children.addAll(subCh );
            }

        }
        nodes.addAll(children);
        return nodes;
    }
}
